/**
 * case1：回文串长度为奇数，可以找到中心点左右两边都相等，即检查i-1和i+1
 * case2：回文串长度为偶数，检查i和i+1
 * @param {string} s 
 * @returns 
 */

var longestPalindrome = function (s) {
    // s长度为1或空，直接返回
    if (s.length < 2) {
        return s
    }

    // 记录初始位置，终止位为start+maxLength
    let start = 0,
        // maxLength至少都会为1，如ab
        maxLength = 1

    function expandAroundCenter(left, right) {
        // 判断 左右两边是否越界 及 左==右
        while (left >= 0 && right < s.length && s[left] === s[right]) {
            let currLength = right - left + 1
            if (currLength > maxLength) {
                maxLength = currLength
                start = left
            }
            left--
            right++
        }
    }

    for (let i = 0; i < s.length; i++) {
        // abcba
        expandAroundCenter(i - 1, i + 1)
        // abba
        expandAroundCenter(i, i + 1)
    }

    return s.substring(start, start + maxLength)
}